// pages/community/community.js - 社区动态页面
const { api } = require('../../utils/api')
const { formatRelativeTime } = require('../../utils/util')

Page({
  data: {
    searchKeyword: '',
    topics: ['推荐'], // 第一个固定为"推荐"，后续从后端加载
    topicIds: [], // 存储话题ID列表（不包括"推荐"）
    activeTopic: 0,
    posts: [],
    loading: false,
    hasMore: true,
    lastCreateTime: null,
    lastPostId: null
  },

  onLoad() {
    console.log('社区页面加载完成');
    this.loadTopics(); // 加载话题列表
    this.loadPosts();
  },

  // 加载话题列表
  loadTopics() {
    api.community.getTopicList()
      .then(res => {
        console.log('话题列表返回', res);
        const topicNames = res.data.map(topic => topic.topicName);
        const topicIds = res.data.map(topic => topic.topicId);
        // 在推荐后面添加话题
        this.setData({
          topics: ['推荐', ...topicNames],
          topicIds: topicIds  // 保存话题ID列表
        });
      })
      .catch(err => {
        console.error('获取话题列表失败', err);
      });
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshPosts();
  },

  // 加载动态列表
  loadPosts() {
    if (this.data.loading) {
      console.log('正在加载中，跳过本次请求');
      return;
    }
    
    if (!this.data.hasMore) {
      console.log('没有更多数据了');
      return;
    }

    // 判断是否选择了话题（activeTopic > 0 表示选择了话题）
    const activeTopic = this.data.activeTopic;
    const isTopicFilter = activeTopic > 0;
    const topicId = isTopicFilter ? this.data.topicIds[activeTopic - 1] : null;

    console.log('开始加载动态列表，当前参数：', {
      activeTopic,
      isTopicFilter,
      topicId,
      lastCreateTime: this.data.lastCreateTime,
      lastPostId: this.data.lastPostId
    });

    this.setData({ loading: true });

    const params = {};
    if (this.data.lastCreateTime) {
      // 去掉时区信息和毫秒，将 2025-11-12T21:44:43.000+08:00 转为 2025-11-12T21:44:43
      let createTime = this.data.lastCreateTime;
      
      // 先去掉时区信息
      if (createTime.includes('+')) {
        createTime = createTime.split('+')[0];
      } else if (createTime.includes('Z')) {
        createTime = createTime.replace('Z', '');
      }
      
      // 再去掉毫秒部分
      if (createTime.includes('.')) {
        createTime = createTime.split('.')[0];
      }
      
      params.createTime = createTime;
    }
    if (this.data.lastPostId) {
      params.postId = this.data.lastPostId;
    }

    console.log('发送请求参数：', params);

    // 根据是否选择话题调用不同的API
    const apiCall = isTopicFilter ? 
      api.community.getPostsByTopicId(topicId, params) : 
      api.community.getPostList(params);

    apiCall
      .then(res => {
        console.log('获取动态列表成功，返回数据量：', res.data?.length || 0);
        
        // 处理返回的数据
        const newPosts = this.formatPosts(res.data || []);
        
        // 判断是否还有更多数据
        const hasMore = newPosts.length > 0;
        
        this.setData({
          posts: [...this.data.posts, ...newPosts],
          loading: false,
          hasMore: hasMore
        });

        console.log('更新后状态：', {
          总帖子数: this.data.posts.length,
          本次新增: newPosts.length,
          hasMore: hasMore
        });

        // 更新分页参数
        if (newPosts.length > 0) {
          const lastPost = newPosts[newPosts.length - 1];
          console.log('保存分页参数：', {
            postId: lastPost.postId,
            createTime: lastPost.createTime
          });
          this.setData({
            lastCreateTime: lastPost.createTime,
            lastPostId: lastPost.postId
          });
        }
      })
      .catch(err => {
        console.error('获取动态列表失败', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
  },

  // 刷新动态列表
  refreshPosts() {
    this.setData({
      posts: [],
      lastCreateTime: null,
      lastPostId: null,
      hasMore: true
    });
    this.loadPosts();
  },

  // 格式化动态数据
  formatPosts(posts) {
    return posts.map(post => {
      // 解析图片 URL
      let images = [];
      try {
        if (post.imageUrls) {
          // 尝试标准 JSON 解析
          try {
            images = JSON.parse(post.imageUrls);
          } catch (e) {
            // 如果失败，尝试处理非标准格式 [url1,url2]
            console.log('尝试解析非标准格式的imageUrls:', post.imageUrls);
            const urlStr = post.imageUrls.trim();
            if (urlStr.startsWith('[') && urlStr.endsWith(']')) {
              // 移除首尾的方括号
              const content = urlStr.slice(1, -1);
              // 按逗号分割（注意：URL中可能包含逗号）
              // 使用更智能的分割方式
              images = content.split(/,(?=http)/).map(url => url.trim());
            }
          }
          console.log('解析后的图片数组:', images);
        }
      } catch (e) {
        console.error('解析图片URL失败', e, post.imageUrls);
      }

      // 格式化时间
      let timeStr = '刚刚';
      if (post.createTime) {
        try {
          const timestamp = new Date(post.createTime).getTime();
          timeStr = formatRelativeTime(timestamp);
        } catch (e) {
          timeStr = post.createTime;
        }
      }

      return {
        id: post.postId,
        postId: post.postId,
        userId: post.userId,
        username: post.createBy || '运动达人',
        avatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f393f5c29478a7b382748e71c1d68ebb.png',
        time: timeStr,
        content: post.content || '',
        images: images,
        likes: post.likeCount || 0,
        comments: post.commentCount || 0,
        liked: false,
        bookmarked: false,
        showComments: false,
        createTime: post.createTime,
        viewCount: post.viewCount || 0
      };
    });
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 执行搜索
  onSearch() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      });
      return;
    }
    
    // TODO: 实现搜索功能
    wx.showToast({
      title: '搜索功能开发中',
      icon: 'none'
    });
  },

  // 选择话题
  selectTopic(e) {
    const index = e.currentTarget.dataset.index;
    
    console.log('切换话题：', {
      从: this.data.activeTopic,
      到: index,
      话题名称: this.data.topics[index]
    });
    
    this.setData({
      activeTopic: index,
      // 重置分页参数
      posts: [],
      lastCreateTime: null,
      lastPostId: null,
      hasMore: true
    });
    
    // 重新加载数据
    this.loadPosts();
  },

  // 跳转到发布页面
  goToPublish() {
    wx.navigateTo({
      url: '/pages/publish/publish'
    });
  },

  // 切换点赞
  toggleLike(e) {
    const { id, index } = e.currentTarget.dataset;
    const post = this.data.posts[index];
    
    // 乐观更新 UI
    this.setData({
      [`posts[${index}].liked`]: !post.liked,
      [`posts[${index}].likes`]: post.liked ? post.likes - 1 : post.likes + 1
    });
    
    // 调用 API
    const apiCall = post.liked ? api.community.unlikePost : api.community.likePost;
    apiCall(id)
      .then(() => {
        console.log('点赞操作成功');
      })
      .catch(err => {
        console.error('点赞操作失败', err);
        // 失败时回滚
        this.setData({
          [`posts[${index}].liked`]: post.liked,
          [`posts[${index}].likes`]: post.likes
        });
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        });
      });
  },

  // 跳转到评论
  goToComments(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?type=post&id=${id}`
    });
  },

  // 跳转到详情页
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?type=post&id=${id}`
    });
  },

  // 预览图片
  previewImages(e) {
    const { index, images } = e.currentTarget.dataset;
    wx.previewImage({
      current: images[index],
      urls: images
    });
  },

  // 切换收藏
  toggleBookmark(e) {
    const { id, index } = e.currentTarget.dataset;
    const post = this.data.posts[index];
    
    // 乐观更新 UI
    this.setData({
      [`posts[${index}].bookmarked`]: !post.bookmarked
    });
    
    // TODO: 调用收藏 API
    wx.showToast({
      title: post.bookmarked ? '已取消收藏' : '已收藏',
      icon: 'success'
    });
  },

  // 跳转到话题
  goToTopic(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?type=topic&id=${id}`
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshPosts();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    console.log('触发 onReachBottom，开始加载更多');
    this.loadPosts();
  }
});
